<template>
  <div class="page-wrapper">
    <div class="app-container">
      <!-- 页面头部 -->
      <PageHeader back-text="返回" back-type="back" :title="projectInfo.proName || '加载中...'" />

      <!-- 项目详情卡片 -->
      <ProjectDetail :project-info="projectInfo" :loading="projectLoading" />

      <!-- 项目计划卡片 -->
      <el-card class="box-card receive-money-card mb-6">
        <template #header>
          <div class="flex justify-between items-center">
            <div class="card-header-left">
              <span class="title">项目计划</span>
            </div>
            <div class="flex items-center" style="gap: 12px">
              <ProjectStatusDisplay label="项目计划审核状态" :status-options="approval_commit_status"
                :status-value="planAuditStatusValue" />
              <el-button type="primary" icon="Refresh" @click="loadAuditList"
                :loading="auditTableLoading">刷新</el-button>
            </div>
          </div>
        </template>
        <el-table v-loading="auditTableLoading" :data="auditList" border style="width: 100%" class="flow-table">
          <el-table-column label="付款节点" prop="nodeTitle" width="220" align="left" fixed="left">
            <template #default="scope">
              <el-tooltip :content="scope.row.nodeTitle" placement="top" :disabled="!scope.row.nodeTitle">
                <span class="text-overflow node-title-chip">{{ scope.row.nodeTitle || '-' }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="技术流程" prop="techFlow" width="240" align="left" fixed="left">
            <template #default="scope">
              <el-tooltip :content="scope.row.techFlow" placement="top" :disabled="!scope.row.techFlow">
                <span class="text-overflow tech-flow-display">{{ scope.row.techFlow || '-' }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="工作内容" prop="workContent" width="300" align="left" :show-overflow-tooltip="true" />
          <el-table-column width="160" label="计划开始时间" align="center" prop="planStartTime" />
          <el-table-column width="160" label="计划完成时间" align="center" prop="planEndTime" />
          <el-table-column label="详细工作计划" prop="detailWorkPlan" align="left" width="300"
            :show-overflow-tooltip="true" />
          <el-table-column width="140" label="占比(%)" align="center">
            <template #default="scope">{{ formatPercentage(scope.row.planRatio) || '-' }}</template>
          </el-table-column>
          <el-table-column width="120" label="人员(人)" align="center" prop="staffAmount" />
          <el-table-column width="120" label="工天(天)" align="center" prop="workDays" />
          <el-table-column width="150" label="总人工天(天)" align="center" prop="totalStaffDays" />
          <el-table-column width="180" label="单位绩效(元/人/天)" align="center">
            <template #default="scope">{{ scope.row.unitPerf ? formatAmount(scope.row.unitPerf) : '-' }}元</template>
          </el-table-column>
          <el-table-column width="180" label="分项绩效(元)" align="center">
            <template #default="scope">{{ formatAmount(scope.row.planPerf) || 0 }}元</template>
          </el-table-column>
          <el-table-column width="140" label="差旅(元)" align="center">
            <template #default="scope">{{ scope.row.travelCost ? formatAmount(scope.row.travelCost) : '-' }}元</template>
          </el-table-column>
          <el-table-column width="140" label="办公费(元)" align="center">
            <template #default="scope">{{ scope.row.officeCost ? formatAmount(scope.row.officeCost) : '-' }}元</template>
          </el-table-column>
          <el-table-column width="140" label="A1(元)" align="center">
            <template #default="scope">{{ scope.row.a1Cost ? formatAmount(scope.row.a1Cost) : '-' }}元</template>
          </el-table-column>
          <el-table-column width="140" label="A2(元)" align="center">
            <template #default="scope">{{ scope.row.a2Cost ? formatAmount(scope.row.a2Cost) : '-' }}元</template>
          </el-table-column>
          <el-table-column width="180" label="总绩效(元)" align="center">
            <template #default="scope">{{ formatAmount(scope.row.totalPerf) || 0 }}元</template>
          </el-table-column>
          <el-table-column label="成本说明" prop="costDescription" align="left" width="260" :show-overflow-tooltip="true" />
          <el-table-column label="备注" prop="remark" align="left" width="260" :show-overflow-tooltip="true" />
          <template #empty>
            <el-empty description="暂无项目计划数据" />
          </template>
        </el-table>
      </el-card>

      <!-- 审核操作组件（与项目审核页一致风格） -->
      <AuditAction :loading="auditLoading" @audit="handleAuditAction" />
    </div>

    <!-- 删除了级联展开对话框，改为直接表格展示auditList -->
  </div>
</template>

<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router';
import { getProDetail } from '@/api/project/init/proInfo';
import type { ProInfoVO } from '@/api/project/init/proInfo/types';
import { getPlanAuditList } from '@/api/project/receive/index';
import type { ProPlanAuditVO } from '@/api/project/receive/types';
import PageHeader from '@/views/project/components/PageHeader/index.vue';
import ProjectDetail from '@/views/project/components/ProjectDetail.vue';
import ProjectStatusDisplay from '@/views/project/components/ProjectStatusDisplay.vue';
import AuditAction from '@/components/AuditAction/index.vue';
import { audit } from '@/api/other/approval/index';
import type { ApprovalAuditBo } from '@/api/other/approval/types';
import { formatAmount } from '@/components/NumberInput';

const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();
const { node_split_status, approval_commit_status } = toRefs<any>(proxy?.useDict('node_split_status', 'approval_commit_status'));

// 项目信息
const projectInfo = ref<Partial<ProInfoVO>>({});
const projectLoading = ref(false);
const planAuditStatusValue = computed(() => {
  const anyInfo = projectInfo.value as any;
  return (anyInfo && (anyInfo.planAuditStatus ?? anyInfo.planAuditstatus ?? anyInfo.plan_audit_status)) ?? '0';
});

// 审核列表（以flow为最小单位）
const auditList = ref<ProPlanAuditVO[]>([]);
const auditTableLoading = ref(false);

// 审核相关
const auditLoading = ref(false);

// 流程查看对话框
const flowDialogVisible = ref(false);
const flowList = ref<any[]>([]);
const currentPlanTechFlow = ref('');
const currentPlanNode = ref<any>(null);

// 加载项目详情
const getProjectDetail = async () => {
  const proId = route.params.proId as string;
  if (!proId) {
    ElMessage.error('项目ID不能为空');
    return;
  }
  try {
    projectLoading.value = true;
    const res = await getProDetail(proId);
    projectInfo.value = res.data || {};
  } catch (error) {
    console.error('获取项目信息失败:', error);
    ElMessage.error('获取项目信息失败');
  } finally {
    projectLoading.value = false;
  }
};

// 加载审核聚合列表
const loadAuditList = async () => {
  const proId = route.params.proId as string;
  if (!proId) {
    ElMessage.error('项目ID不能为空');
    return;
  }
  try {
    auditTableLoading.value = true;
    const res = await getPlanAuditList(proId);
    auditList.value = res.data || [];
  } catch (error) {
    console.error('获取项目计划审核列表失败:', error);
    ElMessage.error('获取项目计划审核列表失败');
  } finally {
    auditTableLoading.value = false;
  }
};

// 行样式（复用编辑态的类名，但此页不会进入编辑态，仅保持统一样式）
const planRowClassName = () => '';

// 百分比格式化
const formatPercentage = (value: number | string) => {
  if (value === null || value === undefined || value === '') return '';
  const num = typeof value === 'number' ? value : Number(value);
  if (Number.isNaN(num)) return '';
  return `${num.toFixed(2)}%`;
};

// 审核提交
const handleAuditAction = (data: { status: string; idea: string }) => {
  auditLoading.value = true;
  const auditData: ApprovalAuditBo = {
    businessId: projectInfo.value.id as any,
    businessType: 'PROJECT-SPLIT-PLAN',
    status: data.status,
    idea: data.idea
  } as ApprovalAuditBo;

  audit(auditData)
    .then(() => {
      ElMessage.success('审核成功');
      router.push('/index');
    })
    .catch(() => {
      auditLoading.value = false;
    });
};

onMounted(() => {
  getProjectDetail();
  loadAuditList();
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

/* 复用 edit.vue 的关键样式，保留列宽与省略号表现 */
.receive-money-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 12px;
}

.card-header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.card-header-left .title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.receive-money-list {
  width: 100%;
  overflow-x: auto;
  min-width: 1330px;
}

.empty-state {
  padding: 40px 0;
}

.list-header {
  display: flex;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border: 1px solid #e4e7ed;
  border-radius: 8px 8px 0 0;
  padding: 12px 0;
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.header-cell {
  padding: 0 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-right: 1px solid #e4e7ed;
  text-align: center;
}

.header-order {
  flex: 1 0 120px;
  min-width: 120px;
}

.header-title {
  flex: 2 0 620px;
  min-width: 620px;
}

.header-remark {
  flex: 1 0 320px;
  min-width: 320px;
}

.header-status {
  flex: 1 0 150px;
  min-width: 150px;
}

.header-action {
  flex: 1 0 150px;
  min-width: 150px;
}

.header-cell.left-align {
  justify-content: flex-start;
  text-align: left;
}

.header-cell:last-child {
  border-right: none;
}

.receive-node-item {
  border: 1px solid #e4e7ed;
  border-top: none;
}

.receive-node-item:last-child {
  border-radius: 0 0 8px 8px;
}

.receive-node-row {
  display: flex;
  background-color: #ffffff;
  transition: all 0.2s ease;
  cursor: default;
  min-height: 60px;
}

.receive-node-row:hover {
  background-color: #f5f7fa;
}

.node-cell {
  padding: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-right: 1px solid #f0f0f0;
  font-size: 14px;
  text-align: center;
}

.node-cell.left-align {
  justify-content: flex-start;
  text-align: left;
}

.node-cell:last-child {
  border-right: none;
}

.node-order {
  flex: 1 0 120px;
  min-width: 120px;
}

.node-title {
  flex: 2 0 620px;
  min-width: 620px;
}

.node-remark {
  flex: 1 0 320px;
  min-width: 320px;
}

.node-status {
  flex: 1 0 150px;
  min-width: 150px;
}

.node-action {
  flex: 1 0 150px;
  min-width: 150px;
}

.expand-cell {
  justify-content: center;
  display: flex;
  align-items: center;
  padding-left: 0;
  padding-right: 0;
}

.expand-cell .expand-button {
  width: 140px;
  min-width: 140px;
  max-width: 140px;
  padding: 8px 14px;
  font-size: 13px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  margin: 0 auto;
}

.expand-cell :deep(.el-icon) {
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 与编辑页一致的展开按钮基础样式与状态样式 */
.expand-button {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  padding: 8px 12px;
  border: 2px solid #d1d5db;
  border-radius: 8px;
  background-color: #ffffff;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
  font-weight: 500;
  color: #6b7280;
  min-width: 80px;
}

.expand-button:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
  color: #409eff;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.2);
}

.expand-button.expanded {
  border-color: #409eff;
  background-color: #409eff;
  color: #ffffff;
}

.expand-button.expanded:hover {
  background-color: #3b82f6;
  border-color: #3b82f6;
}

.expand-text {
  font-weight: 600;
  letter-spacing: 0.5px;
}

.expand-arrow {
  display: flex;
  align-items: center;
  justify-content: center;
  transition: transform 0.3s ease;
  width: 16px;
  height: 16px;
}

.expand-arrow.rotated {
  transform: rotate(180deg);
}

.text-overflow {
  display: block;
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  text-align: center;
  box-sizing: border-box;
  max-width: 100%;
  position: relative;
}

.left-align .text-overflow {
  text-align: left;
}

.list-header,
.receive-node-row {
  display: flex;
  width: 100%;
  min-width: 1330px;
}

.plan-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px 0 16px 0;
  border-bottom: 2px solid #e1e6f0;
}

.plan-header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.plan-icon {
  font-size: 18px;
  color: #409eff;
}

.plan-title {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.plan-header-actions {
  display: flex;
  gap: 8px;
}

.plan-list {
  margin-top: 16px;
}

.plan-op-buttons {
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.plan-op-buttons :deep(.el-button) {
  padding: 0 6px;
}

.tech-flow-display {
  background-color: #f0f9ff;
  padding: 8px 12px;
  border-radius: 6px;
  border-left: 4px solid #409eff;
  font-weight: 500;
  color: #1e40af;
  display: block;
  line-height: 1.4;
}

.node-title-chip {
  background-color: #fff7ed;
  padding: 6px 10px;
  border-radius: 6px;
  border-left: 4px solid #f59e0b;
  font-weight: 500;
  color: #9a3412;
  display: inline-block;
  max-width: 100%;
  line-height: 1.4;
}

.flow-table {
  width: 100%;
}

.flow-table :deep(.el-table__cell) {
  padding: 8px 0;
}

.flow-table :deep(.text-overflow) {
  text-align: left;
}

.calculated-value {
  font-weight: 600;
  color: #409eff;
  background-color: #f0f9ff;
  padding: 4px 8px;
  border-radius: 4px;
  border: 1px solid #e1f5fe;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
</style>
